<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-11-29 16:36:58
 * @LastEditors: Andy
 * @LastEditTime: 2023-01-13 18:40:50
-->
<template>
  <x-dialog
    :title="title"
    :show.sync="visible"
    v-if="visible"
    :before-close="handleClose"
    width="60%"
    @onCancel="handleClose"
    @onSubmit="handleSubmit"
  >
    <el-form
      :model="params"
      class="demo-form-inline"
      ref="params"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item :label="$t('system.tenant.tenantName')" prop="tenantName">
            <el-input
              v-model="params.tenantName"
              :placeholder="$t('system.tenant.tenantNamePlaceholder')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.tenant.enterpriseAbbreviation')" prop="shortName">
            <el-input
              v-model="params.shortName"
              :placeholder="$t('system.tenant.shortNamePlaceholder')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('system.tenant.enterpriseLogo')" prop="logo">
            <ImgUpload ref="tenantAvatarCom" :value="params.logo"></ImgUpload>
            <!-- <el-input v-model="params.logo" :placeholder="$t('system.tenant.logo')"></el-input> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.tenant.loginAccount')" prop="adminUsername">
            <el-input
              v-model="params.adminUsername"
              :placeholder="$t('system.tenant.autoGenerate')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!params.id">
          <el-form-item :label="$t('system.tenant.loginPassword')" prop="loginPassword">
            <el-input
              show-password
              type="password"
              v-model="params.loginPassword"
              :placeholder="$t('system.tenant.loginPassword')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.tenant.contactName')" prop="adminRealName">
            <el-input
              v-model="params.adminRealName"
              :placeholder="$t('system.tenant.contactName')"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.tenant.cellPhone')" prop="adminMobile">
            <el-input v-model="params.adminMobile" :placeholder="$t('system.tenant.cellPhone')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('system.dict.enable')" prop="state">
            <x-radio-group :listData="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </x-dialog>
</template>
<script>
  import { encrypt, omit, throttle } from '@package/utils'
  import { checkMobilePhone, checkPwd } from '@/common/utils/validate.js'
  import { tenantAdd, tenantUpdate } from '../api/tenant.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import ImgUpload from './imgUpload.vue'

  export default {
    components: { ImgUpload },
    props: {
      dictOptions: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        visible: false,
        title: this.$t('common.add'),
        params: {
          tenantName: '', // Enterprise name
          shortName: '', // Enterprise abbreviation
          logo: 'logo',
          adminUsername: '', // Login account
          loginPassword: '', // Login password
          adminRealName: '', // Contact name
          adminMobile: '',
          state: '1'
        },
        rules: {
          tenantName: [
            { required: true, message: this.$t('system.tenant.tenantNamePlaceholder'), trigger: 'blur' },
            { min: 1, max: 100, trigger: 'blur' }
          ],
          shortName: [
            { required: true, message: this.$t('system.tenant.shortNamePlaceholder'), trigger: 'blur' },
            { min: 1, max: 100, trigger: 'blur' }
          ],
          // logo: [{ required: true, message: this.$t('system.tenant.logo'), trigger: 'blur' }],
          adminUsername: [{ required: true, message: this.$t('system.tenant.loginAccount'), trigger: 'blur' }],
          loginPassword: [
            { required: true, message: this.$t('system.tenant.loginPassword'), trigger: 'blur' },
            { min: 6, max: 50, message: this.$t('system.user.pwdLengthPlaceholder'), trigger: 'blur' },
            { validator: this.validatePwd, trigger: 'blur' }
          ],
          adminRealName: [{ required: true, message: this.$t('system.tenant.contactName'), trigger: 'blur' }],
          adminMobile: [
            { required: true, message: this.$t('system.tenant.cellPhone'), trigger: 'blur' },
            { validator: this.validatePhone, trigger: 'blur' }
          ],
          state: [{ required: true, message: this.$t('system.dict.statePlaceholder'), trigger: 'blur' }]
        }
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('common.edit')
          this.$nextTick(() => {
            this.params = JSON.parse(JSON.stringify(info))
            this.params.state += ''
          })
        } else {
          this.title = this.$t('common.add')
        }
      },
      handleClose() {
        this.params = {
          tenantName: '', // Enterprise name
          shortName: '', // Enterprise abbreviation
          logo: 'logo',
          adminUsername: '', // Login account
          loginPassword: '', // Login password
          adminRealName: '', // Contact name
          adminMobile: '',
          state: ''
        }
        this.params = omit(this.params, 'id')
        this.$refs.params.resetFields()
        this.visible = false
      },
      handleSubmit: throttle(function () {
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const loginPassword = encrypt(this.params.loginPassword)
            const param = {
              ...this.params,
              logo: this.$refs.tenantAvatarCom.imgUrl,
              upmsUserDto: {
                username: this.params.adminUsername,
                realName: this.params.adminRealName,
                password: this.params.loginPassword ? loginPassword : undefined,
                userType: 0,
                mobile: this.params.adminMobile,
                workStatus: 0,
                onlineStatus: 0,
                state: 0
              }
            }
            const { code, msg } = param.id ? await tenantUpdate(param) : await tenantAdd(param)
            if (code === EnumApiCode.Success) {
              param.id
                ? this.$message.success(this.$t('common.editSuccess'))
                : this.$message.success(this.$t('common.newSuccess'))
              this.$emit('handleSuccess')
              this.handleClose()
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        })
      }, 1000),
      /**
       * 号码验证
       *
       * @param {*} rule
       * @param {*} value 参数
       * @param {*} callback
       */
      validatePhone(rule, value, callback) {
        if (value && value !== '' && !checkMobilePhone(value)) {
          callback(new Error(this.$t('system.user.PleasePhoneRight')))
        } else {
          callback()
        }
      },
      validatePwd(rule, value, callback) {
        if (value && value !== '' && !checkPwd(value)) {
          callback(new Error(this.$t('system.user.PasswordMode')))
        } else {
          callback()
        }
      }
    }
  }
</script>
